#include <arpa/inet.h>
#include <cstring>
#include <netdb.h>
#include <netinet/in.h> 
#include <unistd.h>
#include <stdlib.h>
#include <string.h>

#include "socket.h"
#include "message.pb.h"

#include <iostream>

using namespace std;


int main(int argc, char* argv[]) {
  GOOGLE_PROTOBUF_MIN_PROTOC_VERSION;

  char host[255] = "127.0.0.1";
//  char host[255];
  unsigned short port = 7070;

//  gethostname(host, 255);
  Socket* sock = new Socket;
  if (!sock->Create()) {
    cerr << " Error creating " << endl;
    exit(1);
  }

  if (sock->Connect(host, port)) {
    Command command;

    // Iterate over the args and append them to command string
    for (int i = 1; i < argc; i++) {
      command.add_command(argv[i]);
    }
    string c_string;
    command.SerializeToString(&c_string);
    size_t length = c_string.length();
    if (length <= 0) {
      cerr << "No command " << endl;
      exit(1);
    }

    sock->Send(&length, sizeof(length));
    char* tmp = new char[length + 1];
    strcpy(tmp, c_string.c_str());
    sock->Send(tmp, length);

    // Wait for reponse
    int rv = sock->Receive(&length, sizeof(length));
    while (rv <= 0) {
      rv = sock->Receive(&length, sizeof(length));
    }
    //cerr << "length " << length << endl;
    sock->Close();
  } else {
    cerr << "Could not connect "<< endl;
  }
  return 0;
}

